package com.guet.niit.Login.controller.user;

import com.guet.niit.User.service.UserService;
import com.guet.niit.util.UserBacktrack;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

import java.net.URL;
import java.util.ResourceBundle;

public class UpdatePasswordFxController implements Initializable {

    public static UpdatePasswordFxController updatePasswordFxController;

    @FXML
    private ImageView backtrack;

    @FXML
    private PasswordField newPassword;

    @FXML
    private PasswordField checkNewPassword;

    @FXML
    private Label validation;

    @FXML
    private Button changePassword;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        updatePasswordFxController = this;
    }

    /**
     * 返回用户菜单
     * @param mouseEvent
     */
    public void backtrack(MouseEvent mouseEvent) {
        UserBacktrack.backtrack(UpdatePasswordFxController.class);
    }

    /**
     * 检查用户再次输入的密码是否与新密码一致
     * @param mouseEvent
     */
    public void checkInputPassword(MouseEvent mouseEvent) {
        //获取用户修改的密码
        String newPasswords = newPassword.getText();
        String checkNewPasswords = checkNewPassword.getText();
        if (checkNewPasswords.equals(newPasswords)){
            validation.setText("");
            changePassword.setDisable(false);
        }else {
            validation.setText("您两次输入的密码不一致！");
            changePassword.setDisable(true);
        }
    }

    /**
     * 修改个人密码
     * @param mouseEvent
     */
    public void changePassword(MouseEvent mouseEvent) {
        //获取当前登录用户的id
        String name = Thread.currentThread().getName();
        long userId = Long.parseLong(name);
        //获取用户修改的密码
        String latestPassword = newPassword.getText();
        //查询用户当前密码
        UserService userService = new UserService();
        String currentPassword = userService.returnPassword(userId);
        if (latestPassword.equals(currentPassword)){
            //新密码与原密码相同则弹窗提示用户
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText(null);
            alert.setContentText("您输入的密码与原密码相同,请换一个!");
            alert.showAndWait();
        }else {
            //新密码与原密码不相同则修改密码
            userService.updatePassword(userId,latestPassword);
            //修改密码成功后返回用户菜单
            UserBacktrack.backtrack(UpdatePasswordFxController.class);
        }
    }

    /**
     * 重置用户已经输入的密码
     * @param mouseEvent
     */
    public void resetInput(MouseEvent mouseEvent) {
        newPassword.setText("");
        checkNewPassword.setText("");
    }
}
